#include "collection.h"
#include "stdlib.h"

/**
 * 初始化单链表头结点
 */
void init_s_node_head(Link_List *list)
{
    if(!list) return;
    list->s_size = 0;
    list->s_head = (S_Node *) malloc(sizeof(S_Node));
    list->s_head->next = NULL;
    list->s_head->data = NULL;
}

/**
 * 初始化双链表头结点
 */
void init_d_node_head(Link_List *list)
{
    if(!list) return;
    list->d_size = 0;
    list->d_head = (D_Node *) malloc(sizeof(D_Node));
    list->d_head->prior = NULL;
    list->d_head->next = NULL;
    list->d_head->data = NULL;
}

/**
 * 初始化循环单链表头结点
 */
void init_s_c_node_head(Link_List *list)
{
    if(!list) return;
    list->s_size = 0;
    list->s_head = (S_Node *) malloc(sizeof(S_Node));
    list->s_head->next = list->s_head;
    list->s_head->data = NULL;
}

/**
 * 初始化循环双链表头结点
 */
void init_d_c_node_head(Link_List *list)
{
    if(!list) return;
    list->d_size = 0;
    list->d_head = (D_Node *) malloc(sizeof(D_Node));
    list->d_head->prior = list->d_head;
    list->d_head->next = list->d_head;
    list->d_head->data = NULL;
}

/**
 * 获取单链表指定位置的数据元素
 */
Stu *get_s_node_elem(Link_List *list, int index)
{
    int i = 0;
    S_Node *p = list->s_head->next;
    while(p && ++i < index) p = p->next;
    if(!p || i > index) return NULL;
    return p->data;
}

/**
 * 新增单链表指定位置的数据元素
 */
int insert_s_node_elem(Link_List *list, int index, Stu *stu)
{
    int i = -1;
    S_Node *p = list->s_head;
    while(p && ++i < index -1) p = p->next;
    if(!p || i > index - 1) return -1;
    S_Node *s_node = (S_Node *) malloc(sizeof(S_Node));
    s_node->next = p->next;
    s_node->data = stu;
    p->next = s_node;
    list->s_size += 1;
    return 1;
}

/**
 * 删除单链表指定位置的数据元素
 */
Stu *delete_s_node_elem(Link_List *list, int index)
{
    int i = -1;
    S_Node *p = list->s_head;
    while(p->next && ++i < index -1) p = p->next;
    if(!p->next || i > index - 1) return NULL;
    S_Node *q = p->next;
    p->next = q->next;
    Stu *stu = q->data;
    free(q);
    list->s_size -= 1;
    return stu;
}

/**
 * 初始化顺序表
 */
void init_sq_list(Sq_List *list)
{
    if(!list) return;
    list->arr = (Stu *) malloc(sizeof(Stu) * LIST_INIT_SIZE);
    if(!list->arr) return;
    list->size = 0;
    list->list_size = LIST_INIT_SIZE;
}

/**
 * 插入顺序表
 */
void insert_sq_list(Sq_List *list, int index, Stu *stu)
{
    if(index > list->size + 1 || index < 1) return;
    if(list->size + 1 > list->list_size) {
        Stu *newbase = (Stu *) realloc(list->arr, sizeof(Stu) * (list->list_size + LIST_INCREMENT_SIZE));
        if(!newbase) return;
        list->arr = newbase;
        list->list_size += LIST_INCREMENT_SIZE;
    }
    Stu *arr = list->arr + list->size;
    for(int i = list->size; i > index - 1; i--) {
        *arr = *(arr - 1);
        arr--;
    }
    *arr = *stu;
    list->size++;
}
